var sendtext = document.getElementById('sendtext')
var sendbutton = document.getElementById('sendbutton')
var text = document.getElementById('text')
var container = document.getElementById('container')
var indiv = document.getElementById('in')
var login = document.getElementById('in-bu')

var tan = document.getElementById('tan')
var tancontent = document.getElementById('tan-content')
var color = ["#7efff5",
    "#f8a5c2", "#9AECDB", "#c7ecee", "#f1f2f6", "#18dcff", "#f78fb3", "#0fbcf9", "#ffeaa7", "#cd84f1"
]
var signed = new Boolean();

login.onclick = function() {
    butext.innerHTML = "Let's go";
    butext.classList.add("inpcc");
}



var heart = 0; //心跳
var rec = 0; //重连次数
var reCe = false; //是否因为重连才谈的框
//初始化websocket

function cls() {
    document.getElementsByClassName('tan')[0].style.display = 'none'

    reCe = false;


}

function socketinit(socket) {

    socket.addEventListener('open', function(e) {
        signed = true;
        rec = 0;
        heart = 0;
        if (reCe) {
            tan.style.display = "none";
            reCe = false;
        }
    })
    socket.addEventListener('message', function(e) {
        var data = JSON.parse(e.data)
        if (data.type == 'hbt') {
            heart = 0;

            return;
        }
        n = parseInt(Math.random() * color.length);
        var dv = document.createElement('div')
            // dv.innerHTML = data.message
        const p = document.createElement('p')


        if (!signed) {
            tan.style.display = "block"
            tancontent.innerHTML = "宁还没有连接成功哦，再等等或者刷新试试~"
        } else if (data.type != 'login' && data.type != "logout") {
            var emj = data.data.match(/<img[^>]+>/g);
            var mactest = data.data.replace(/<img[^>]+>/g, '')
            var emjcount;
            if (emj == null) {
                emjcount = 0;

            } else {
                emjcount = emj.length;
            }

            if (mactest.length + emjcount > 50) {

                return;
            }
            p.innerHTML = data.data
            dv.appendChild(p)
            dv.className = "msg";
            // var dvwidth = text.offsetWidth;
            dv.style.backgroundColor = color[n];
            text.prepend(dv); //在已有节点前插入盒子
            $(".text div:first-child").hide();
            $('.text div:first-child').fadeIn("slow");
            console.log(e.data)
        }
    })
    socket.addEventListener("close", (event) => {
        tan.style.display = "block"
        tancontent.innerHTML = "啊噢，不小心断线了.."
        reCe = true;
    })

    socket.addEventListener("error", (event) => {
        console.log("发生错误，重连...");
        tan.style.display = "block"
        reCe = true;
        tancontent.innerHTML = "出错了，重连中..";
        // recont();

    })
}
var count = 0;
var tipMsg = false;
var prm = +new Date();
var sendmsg = function() {
    var value = sendtext.value;
    var t2 = +new Date();
    if (t2 - prm > 1000 * 10) {
        prm = t2;
        count = 0;
    }
    if (count > 5) {
        tan.style.display = "block"
        tancontent.innerHTML = "宁频率太快了，请稍后再发"
        tipMsg = true
        return;
    }
    if (value != '') {
        if (value.length > 100) {
            tan.style.display = "block"
            tancontent.innerHTML = "内容过长"
            tipMsg = true
            return;
        }
        if (socket.readyState == 1) {
            socket.send(JSON.stringify({
                    type: 'text',
                    data: value
                })) //给socket发送消息
            sendtext.value = '';
            sendtext.focus();
            count++;
        } else {
            tan.style.display = "block"
            tancontent.innerHTML = "尚未连接，请稍后~"
            tipMsg = true
        }
    } else {
        tan.style.display = "block"
        tancontent.innerHTML = "不可以发空消息哦"
        tipMsg = true
    }
};

var socket = new WebSocket("ws://localhost:8080/websocket");
socketinit(socket);
login.addEventListener('click', function() {
    setTimeout(function() {
        indiv.style.display = "none"
        container.style.display = "block"
    }, 2000)
    sendbutton.onclick = sendmsg
})

var recont = function() {
    socket = new WebSocket("ws://localhost:8080/websocket");
    socketinit(socket);
}
var wbint = setInterval(function() {
    if (socket.readyState == 0) {
        return;
    }
    if (socket.readyState == 1) {
        socket.send(JSON.stringify({
            type: 'hbt'
        }))
    }

    heart = heart + 1;
    if (heart > 3) {
        console.log("长时间无响应，正在重连...");
        // tan.style.display = "block"
        // tancontent.innerHTML = "长时间无响应，正在重连..."
        rec++;
        if (socket.readyState == 1) {
            socket.close();
        }

        recont();
    }
    //10次的话你真连不上了
    if (rec > 10) {
        clearInterval(wbint);
        console.log("连接失败，请检查网络连接");
        // tan.style.display = "block"
        // tancontent.innerHTML = "连接失败，请检查网络连接"
    }
}, 6000)




//key监听
var key = document.querySelector("#sendtext");
key.onkeydown = function(e) {
    if (e.keyCode == 13) {
        return false;
    }

}
key.addEventListener('keyup', function(e) {
        if (e.keyCode == 13) {
            if (tipMsg) {
                tipMsg = false;
                tan.style.display = 'none';
                return;
            }
            sendmsg();
        }
    })
    // tan.onkeydown =function(e){
    //     return false;
    // }
    // tan.addEventListener('keyup',function(e){
    //     if(e.keyCode==13){
    //         cls();
    //         sendtext.focus();
    //     }
    // })